package com.itheima.app.manager;

import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.exception.BusinessException;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.TaoHua;
import com.itheima.domain.mongo.TaoHuaLike;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.TaoHuaLikeService;
import com.itheima.service.mongo.TaoHuaService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.ErrorResult;
import com.itheima.vo.TaohuaVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

@Component
public class TaoHuaManager {

    @Autowired
    FastFileStorageClient client;
    @Autowired
    FdfsWebServer fdfsWebServer;
    @DubboReference
    TaoHuaService taoHuaservice;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @DubboReference
    UserInfoService userInfoService;
    @DubboReference
    TaoHuaLikeService taoHuaLikeService;

    //发送桃花语音
    public void save(MultipartFile soundFile) throws IOException {

        //将语音上传到fastdfs
        String originalFilename = soundFile.getOriginalFilename();
        String fileName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), fileName, null);
        String url = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

        //保存到taohua对象
        TaoHua taoHua = new TaoHua();
        taoHua.setStatus(0);
        taoHua.setCreated(System.currentTimeMillis());
        taoHua.setSoundUrl(url);
        taoHua.setUserId(UserHolder.get().getId());

        //调用service进行保存
        String save = taoHuaservice.save(taoHua);

        //如果为空 报错    语音为空,未发送成功
        if (StrUtil.isEmpty(save)) {
            throw new BusinessException(ErrorResult.TaoHuaError().getErrMessage());
        }


    }

    //接受语音
    public TaohuaVo AcceptTaoHua() {

        //获取当前用户的id
        Long userId = UserHolder.get().getId();
        //查询redis中今日能接受语音的次数
        String count = stringRedisTemplate.opsForValue().get(ConstantUtil.TAOHUA_COUNT + userId);
        //判断是否有数据 如果没有数据 代表今日还没接收  给个默认的
        if (count == null) {
            count = "8";
            stringRedisTemplate.opsForValue().set(ConstantUtil.TAOHUA_COUNT + userId,count,getSecondNextEarlyMorning(), TimeUnit.SECONDS);
        }else if(!(Integer.valueOf(count)>0)){
            //当次数不大于0 代表没有次数 抛异常
            throw new BusinessException(ErrorResult.CountError().getErrMessage());
        }
        //随机接收一条语音
        TaoHua taoHua = taoHuaservice.randomFind(userId);
        if (taoHua == null){
            throw new BusinessException(ErrorResult.NotError().getErrMessage());
        }
        //更新redis中的次数  注意count为string  所以先转换为int 减去次数后 再转换回去
        stringRedisTemplate.opsForValue().set(ConstantUtil.TAOHUA_COUNT + userId,String.valueOf(Integer.valueOf(count)-1),getSecondNextEarlyMorning(),TimeUnit.SECONDS);

        //成功后保存到桃花喜欢表上
        TaoHuaLike taoHuaLike = new TaoHuaLike();
        taoHuaLike.setCreated(System.currentTimeMillis());
        taoHuaLike.setPublishId(taoHua.getUserId());
        taoHuaLike.setUserId(userId);
        taoHuaLike.setSoundUrl(taoHua.getSoundUrl());
        taoHuaLikeService.save(taoHuaLike);

        //查询语音对应的用户信息  userinfo
        Long huaUserId = taoHua.getUserId();
        UserInfo userInfo = userInfoService.findById(huaUserId);
        TaohuaVo taohuaVo = TaohuaVo.init(userInfo, taoHua);
        //剩余次数设置进去
        taohuaVo.setRemainingTimes(Integer.valueOf(count));

        return taohuaVo;

    }

    //获取当前时间距离凌晨的秒数
    private long getSecondNextEarlyMorning() {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_YEAR,1);
        instance.add(Calendar.HOUR_OF_DAY,0);
        instance.add(Calendar.SECOND,0);
        instance.add(Calendar.MINUTE,0);
        instance.add(Calendar.MILLISECOND,0);
        return (instance.getTimeInMillis()-System.currentTimeMillis())/1000;
    }
}
